import { Inject, Injectable, LOCALE_ID } from "@angular/core";
import { HttpClient, HttpParams } from "@angular/common/http";
import { Observable } from "rxjs";
import { formatDate } from "@angular/common";
import { NzMessageService } from "ng-zorro-antd/message";
import { Clipboard } from '@angular/cdk/clipboard';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  // Menu List
  sysMenuLists: any = [];
  // Head Actived Id
  headActiveId = localStorage.getItem('headActiveId') || -1;
  // user info
  userInfo = null;

  constructor(
    @Inject(LOCALE_ID) private locale: string,
    public httpClient: HttpClient,
    private message: NzMessageService,
    private clipboard: Clipboard
  ) { }

  /**
   * ----------------------------------------------------------------
   * storage
   * ----------------------------------------------------------------
   */
  setStorage = (key: string, val: any) => {
    localStorage.setItem(key, JSON.stringify(val));
  }

  getStorage = (key: string) => {
    try {
      let val = localStorage.getItem(key);
      if (val == null || val == undefined || val == '') {
        return null;
      }
      return val;
    } catch (error) {
      return null;
    }
  }

  removeStorage(key: string) {
    localStorage.removeItem(key);
  }

  /**
   * ----------------------------------------------------------------
   * Common Methods
   * ----------------------------------------------------------------
   */

  // downLoad file Blob
  downLoadBlobFile = (res: any, fileName: string) => {
    let nowTime = formatDate(new Date(), 'yyyyMMddhhmmss', this.locale);
    let blob = new Blob([res], {type : 'application/vnd.ms-excel'});
    let ojectUrl = URL.createObjectURL(blob);
    let a = document.createElement('a');
    
    a.href = ojectUrl;
    a.download = fileName + nowTime;
    a.target = '_blank';
    a.click();
    URL.revokeObjectURL(a.href);
    a.remove();
  }

  // downLoad file Url
  downLoadUrlFile = (url: string, fileName?: string) => {
    let jqIndex = url.lastIndexOf('.');
    let imgTypeStr = url.substring(jqIndex + 1, url.length).toLowerCase();
    let nowTime = formatDate(new Date(), 'yyyyMMddhhmmss', this.locale);
    let typeArrs = ['gif', 'jpg', 'jpeg', 'png', 'svg', 'pdf'];
    let a = document.createElement('a');
    
    a.href = url;
    // a.download = fileName ? fileName + nowTime : '';
    if (typeArrs.includes(imgTypeStr)) {
      a.target = '_blank';
    }
    a.click();
    URL.revokeObjectURL(a.href);
    a.remove();
  }

  /**
   * ----------------------------------------------------------------
   * Common Interfaces
   * ----------------------------------------------------------------
   */
  serviceUrls = {
    dictUrl: '/dict/detail', // 字典查询
    uploadFileUrl: '/common/upload/file', // 上传
    uploadAliyunFileUrl: '/common/upload/ossFile', // 上传 阿里云
    menuListUrl: '/sys/menu/menuQuery', // 菜单list
    querySupplierListUrl: '/supplier/list', // 查询货主
    queryBrandListUrl: '/recycleBrand/list', // 查询回收品牌
    querySeriesListUrl: '/recycleSeries/list', // 查询回收系列
    queryModelListUrl: '/recycleModel/list', // 查询回收机型
    queryMappingListUrl: '/mapping/list' // 查询映射list
  };

  // Menu List
  getMenuListData() {
    return this.httpClient.post(this.serviceUrls.menuListUrl, {});
  }

  // 查询货主(供货商)
  querySupplierList(params: any) {
    return this.httpClient.post(this.serviceUrls.querySupplierListUrl, params).toPromise();
  }

  // 查询品牌List
  getBrandList(params: any) {
    return this.httpClient.post(this.serviceUrls.queryBrandListUrl, params).toPromise();
  }
  // 查询系列List
  getSeriesList(params: any) {
    return this.httpClient.post(this.serviceUrls.querySeriesListUrl, params).toPromise();
  }
  // 查询机型List
  getModelList(params: any) {
    return this.httpClient.post(this.serviceUrls.queryModelListUrl, params).toPromise();
  }
  
  /**
   * 字典查询
   * @param parentKey 
   * @returns 
   */
  dictListData(parentKey: any) {
    let params: any = {
      parentKey: parentKey,
      pageNum: 0,
      pageSize: 0
    };
    return this.httpClient.get(this.serviceUrls.dictUrl, { params: params }).toPromise();
  }

  /**
   * 文件上传
   * @param fileToUpload 
   * @returns 
   */
  uploadFileData(fileToUpload: File, folderName: string = 'folder-common', fileName?: string) {
    const formData: FormData = new FormData();

    formData.append('file', fileToUpload);
    formData.append('name', folderName);
    if (fileName) {
      formData.append('fileName', fileName);
    }
    return this.httpClient.post(this.serviceUrls.uploadFileUrl, formData).toPromise();
  }

  /**
   * 文件上传(阿里云服务)
   * @param fileToUpload 
   * @returns 
   */
  uploadAliyunFileData(fileToUpload: File, folderName: string = 'folder-common', fileName?: string) {
    const formData: FormData = new FormData();

    formData.append('file', fileToUpload);
    formData.append('name', folderName);
    if (fileName) {
      formData.append('fileName', fileName);
    }
    return this.httpClient.post(this.serviceUrls.uploadAliyunFileUrl, formData).toPromise();
  }

  /**
   * 查询映射List
   * @param params 
   * @returns 
   */
  getMappingData(params: any) {
    return this.httpClient.post(this.serviceUrls.queryMappingListUrl, params).toPromise();
  }

  // 查询Dict字典
  async getDictList(parentKey: string) {
    let tmpArr: any = [];
    const res: any = await this.dictListData(parentKey);

    if (res.code == 0) {
      tmpArr = res.data.list || [];
    } else {
      tmpArr = [];
      this.message.error(res.message);
    }
    return tmpArr || [];
  }

  // 获取全部货主（供货商list）
  async getSupplierList() {
    let optionsArrs = [];
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.querySupplierList(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      optionsArrs = records.filter((item: any) => item.name);
    } else {
      this.message.error(res.message);
    }
    return optionsArrs;
  }

  // Copy Content
  copyStr(str: string) {
    this.clipboard.copy(str);
    this.message.success('已成功复制到剪贴板');
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }

  // debounce
  _debounce(fn: any, delay: number) {
    let timer: any = null;
    
    return () => {
      if (timer !== null) {
        clearTimeout(timer);
      }
      timer = setTimeout(fn, delay);
    }
  }
}
